# -*- coding:utf8 -*-
from django.core.handlers.wsgi import WSGIRequest

from functools import wraps
from django.contrib.sessions.backends.db import SessionStore
from django.contrib.sessions.models import Session
from django.shortcuts import redirect

from common.http.whttp import send_error_response_with_message
from django.conf import settings

import datetime


def require_params(params=None, method="GET"):
    """
    指明请求必要的参数，如果请求中不包涵params中指定的参数名，则直接返回错误结果
    :param params: 必须的参数名
    :param method: 请求方法，默认GET
    :param error_handler: 如果请求中不包涵必要的参数，则用error_handler进行处理
    :return:
    """
    def wrapper(func):
        @wraps(func)
        def wrapped(request, *args, **kwargs):
            # 必须的参数列表不为空
            req = request
            if not isinstance(req, WSGIRequest):
                for arg in args:
                    if isinstance(arg, WSGIRequest):
                        req = arg
                        break
            if params:
                m = method.upper()
                query = None
                if hasattr(req, m):
                    query = getattr(req, m)

                if params is not None:
                    if query is None:
                        return send_error_response_with_message(
                            message=u'缺少必须参数 %s' % params)

                    for param in params:
                        if param not in query:
                            return send_error_response_with_message(
                                message=u'缺少必须参数 %s' % param)

            return func(request, *args, **kwargs)
        return wrapped
    return wrapper


def check_login(login_view='/', method="GET"):

    def wrapper(func):
        @wraps(func)
        def wrapped(request, *args, **kwargs):
            req = request
            if not isinstance(req, WSGIRequest):
                for arg in args:
                    if isinstance(arg, WSGIRequest):
                        req = arg
                        break

            if hasattr(req, method):
                query = getattr(req, method)

            if query and "session" in query:
                session_id = query["session"]

                session_model = None
                try:
                    session_model = Session.objects.get(pk=session_id)
                except Session.DoesNotExist:
                    pass

                if not session_model or datetime.datetime.now() > session_model.expire_date:
                    if session_model:
                        session_model.delete()
                    return redirect(u'%s?next=%s' % (login_view, req.path))

                else:
                    session = SessionStore(session_key=session_id)
                    session.set_expiry(getattr(settings, 'SESSION_COOKIE_AGE', 0))
                    session.save()

            else:
                return redirect(u'%s?next=%s' % (login_view, req.path))

            return func(request, *args, **kwargs)
        return wrapped
    return wrapper
